package com.lyy.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

/**
 * 配置springsecurity
 */
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    //用户配置,
    @Bean
    public UserDetailsService userDetailsService(){
        //在内存中配置用户
        InMemoryUserDetailsManager manager=new InMemoryUserDetailsManager();
        manager.createUser(User.withUsername("lyy").password("123").authorities("ROLE_P1").build());
        manager.createUser(User.withUsername("zs").password("456").authorities("ROLE_P2").build());
        return manager;
    }

    //密码加密方式配置
    @Bean
    public PasswordEncoder passwordEncoder(){
        return NoOpPasswordEncoder.getInstance();
    }

    //安全配置
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        //匹配路径时越具体的路径要先匹配
        //放行登录页面,和处理登录请求的url
        http.authorizeRequests().antMatchers("/login","/login.html").permitAll();
        http.authorizeRequests().antMatchers("/","/index.html").permitAll();
        http.authorizeRequests().antMatchers("/res/r1.html").hasRole("P1");
        http.authorizeRequests().antMatchers("/res/r2.html").hasRole("P2");
        http.authorizeRequests().anyRequest().authenticated();
        //注意自定义安全配置时一定要把登录页面和登录url配上,不然访问任何页面都是403,除非最后一行调用父类的config方法
        http.formLogin().loginPage("/login.html").loginProcessingUrl("/login");
    }
}
